<template>
  <view class="container page-with-cunba-nav">
    <!-- 民宿导航栏组件 -->
    <house-nav-bar 
      @nav-height="onNavHeightChange"
      @city-changed="onCityChanged"
      @go-back="handleBack"
    />
    
    <!-- 日期选择器 -->
    <view class="date-selector">
      <swiper 
        class="date-swiper"
        :current="currentSwiperIndex"
        @change="onSwiperChange"
        :disable-touch="false"
        :circular="false"
        :display-multiple-items="1"
        :skip-hidden-item-layout="true"
      >
        <swiper-item 
          v-for="(dateGroup, groupIndex) in dateGroups" 
          :key="groupIndex"
          class="swiper-item"
        >
          <view class="date-week">
            <view 
              class="date-item" 
              :class="{ active: item.isSelected, today: item.isToday }"
              v-for="(item, index) in dateGroup" 
              :key="index"
              @click="selectDate(item.date)"
            >
              <text class="date-month">{{ item.month }}</text>
              <text class="date-day">{{ item.day }}</text>
              <text class="date-week-text">{{ item.weekText }}</text>
            </view>
          </view>
        </swiper-item>
      </swiper>
      
      <!-- 滑动指示器 -->
      <view class="swiper-dots">
        <view 
          class="dot" 
          :class="{ active: index === currentSwiperIndex }"
          v-for="(item, index) in dateGroups" 
          :key="index"
          @click="goToSwiperIndex(index)"
        ></view>
      </view>
    </view>

    <!-- 赛事类型提示 -->
    <view class="match-type-header">
      <text class="current-date">{{ currentDateText }}</text>
    </view>

    <!-- 赛事类型切换标签 -->
    <view class="match-type-tabs">
      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ active: activeMatchType === index }"
          v-for="(type, index) in matchTypes" 
          :key="index"
          @click="switchMatchType(index)"
        >
          <text class="tab-text">{{ type.name }}</text>
        </view>
      </view>
    </view>

    <!-- 调试信息 -->
    <view class="debug-info" style="padding: 10px; background: #f0f0f0; margin: 10px; display: flex; flex-direction: column;" v-if="false">
      <text style="margin-bottom: 5px;">当前比赛类型: {{ (matchTypes[activeMatchType] && matchTypes[activeMatchType].name) || '无' }}</text>
      <text style="margin-bottom: 5px;">比赛数量: {{ currentMatches.length }}</text>
      <text style="margin-bottom: 5px;">activeMatchType: {{ activeMatchType }}</text>
      <text style="margin-bottom: 5px;">选中日期: {{ selectedDate }}</text>
      <text style="margin-bottom: 5px;">加载状态: {{ loading ? '加载中' : '已完成' }}</text>
    </view>

    <!-- 比赛列表 -->
    <view class="match-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">正在加载比赛数据...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-else-if="!currentMatches.length" class="empty-container">
        <text class="empty-text">{{ getEmptyStateText() }}</text>
        <text class="empty-tips">{{ getEmptyStateTips() }}</text>
      </view>
      
      <!-- 使用比赛卡片组件 -->
      <MatchCard 
        v-for="(match, index) in currentMatches" 
        :key="index"
        :match="match"
        :showDebugInfo="false"
        @team-click="viewTeamDetail"
        @watch-click="watchMatch"
      />
    </view>

    <!-- 自定义导航栏 -->
    <cunba-nav-bar :activeIndex="1" @nav-change="onNavChange"></cunba-nav-bar>
  </view>
</template>

<script>
import CunbaNavBar from '@/components/cunba-nav-bar/index.vue'
import MatchCard from '@/components/matchCard/index.vue'
import HouseNavBar from '@/components/house_nav/index.vue'
import { getCalendarData } from '@/api/cunba.js'

export default {
  components: {
    CunbaNavBar,
    MatchCard,
    HouseNavBar
  },
  data() {
    return {
      selectedDate: '',
      activeMatchType: 0,
      loading: false,
      weekDates: [],
      dateGroups: [], // 分组的日期数据
      currentSwiperIndex: 0, // 当前swiper索引
      matchTypes: [],
      matches: [],
      pagination: {
        total: 0,
        currentPage: 1,
        hasMore: false
      },
      // 今天的日期信息
      todayInfo: {
        date: '',
        text: ''
      },

    }
  },
  computed: {
    currentMatches() {
      // 如果没有比赛类型或者没有比赛数据，返回空数组
      if (!this.matchTypes.length || !this.matches.length) {
        return []
      }
      
      // 根据当前选择的比赛类型筛选比赛
      const currentMatchType = this.matchTypes[this.activeMatchType]
      const currentTypeId = currentMatchType && currentMatchType.id
      if (!currentTypeId) {
        return this.processMatches(this.matches)
      }
      
      const filteredMatches = this.matches.filter(match => {
        return match.matchType.id === currentTypeId
      })
      
      return this.processMatches(filteredMatches)
    },
    
    // 当前选中日期的显示文本
    currentDateText() {
      if (!this.todayInfo.text) {
        return ''
      }
      return this.todayInfo.text
    }
  },
  onLoad() {
    this.generateDateGroups()
    // 延迟加载数据，等待导航栏组件初始化完成
    this.$nextTick(() => {
      setTimeout(() => {
        this.loadCalendarData()
      }, 500)
    })
  },

  /**
   * 处理导航栏返回按钮点击事件
   */
  onNavigationBarButtonTap() {
    uni.navigateBack({
      delta: 1
    })
  },
  methods: {
    // 导航栏高度变化回调
    onNavHeightChange(height) {
      this.navBarHeight = height
    },
    
    // 城市切换回调
    onCityChanged(data) {
      console.log('城市已切换:', data)
      // 重新加载日历数据
      this.loadCalendarData({
        date: this.selectedDate,
        page: 1,
        limit: 20
      })
    },
    
    // 返回按钮回调
    handleBack() {
      console.log('村BA日历页面返回按钮点击');
      // HouseNavBar组件已经处理了返回逻辑，这里不需要额外处理
    },
    
    // 生成日期分组数据
    generateDateGroups() {
      const today = new Date()
      const dateGroups = []
      const totalWeeks = 4 // 生成4周的数据
      
      for (let week = 0; week < totalWeeks; week++) {
        const weekDates = []
        const startDate = new Date(today)
        startDate.setDate(today.getDate() + (week * 7) - today.getDay()) // 从周一开始
        
        for (let day = 0; day < 7; day++) {
          const currentDate = new Date(startDate)
          currentDate.setDate(startDate.getDate() + day)
          
          const dateStr = this.formatDate(currentDate)
          const isToday = this.isSameDate(currentDate, today)
          const isSelected = week === 0 && day === today.getDay() // 默认选中今天
          
          weekDates.push({
            date: dateStr,
            month: currentDate.getMonth() + 1,
            day: currentDate.getDate(),
            weekText: this.getWeekText(currentDate.getDay()),
            isToday,
            isSelected: isSelected && week === 0
          })
        }
        dateGroups.push(weekDates)
      }
      
      this.dateGroups = dateGroups
      
      // 设置默认选中今天的日期
      const todayStr = this.formatDate(today)
      this.selectedDate = todayStr
      
      // 设置今天的信息
      this.todayInfo = {
        date: todayStr,
        text: `今天${today.getMonth() + 1}月${today.getDate()}日 ${this.getWeekText(today.getDay())}`
      }
      
      
    },
    
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 判断两个日期是否是同一天
    isSameDate(date1, date2) {
      return date1.getFullYear() === date2.getFullYear() &&
             date1.getMonth() === date2.getMonth() &&
             date1.getDate() === date2.getDate()
    },
    
    // 获取星期文本
    getWeekText(dayOfWeek) {
      const weekTexts = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return weekTexts[dayOfWeek]
    },
    
    // swiper滑动事件
    onSwiperChange(e) {
      this.currentSwiperIndex = e.detail.current
    },
    
    // 跳转到指定的swiper页面
    goToSwiperIndex(index) {
      this.currentSwiperIndex = index
    },
    
    // 处理比赛数据，确保观看按钮显示正确
    processMatches(matches) {
      return matches.map(match => {
        // 创建深拷贝以避免直接修改原数据
        const processedMatch = JSON.parse(JSON.stringify(match))
        
        // 确保每个比赛都有status对象
        if (!processedMatch.status) {
          processedMatch.status = {
            code: 'upcoming',
            text: '未开始',
            statusClass: 'status-upcoming'
          }
        }
        
        // 检查并修复观看信息
        const needsDefaultWatchInfo = !processedMatch.watchInfo || 
                                     !processedMatch.watchInfo.text || 
                                     processedMatch.canWatch === false ||
                                     processedMatch.canWatch === undefined
        
        if (needsDefaultWatchInfo) {
          // 根据比赛状态设置默认的观看信息
          const statusCode = processedMatch.status.code
          const statusText = processedMatch.status.text
          
          if (statusCode === 'upcoming' || statusText === '未开始' || statusText === '即将开始') {
            // 未开始的比赛显示预约按钮
            processedMatch.watchInfo = {
              type: 'reserve',
              text: '预约',
              needReservation: true,
              price: 0,
              watchBtnClass: 'btn-reserve'
            }
            processedMatch.canWatch = true
          } else if (statusCode === 'live' || statusText === '进行中') {
            // 进行中的比赛不显示观看按钮
            processedMatch.watchInfo = null
            processedMatch.canWatch = false
          } else if (statusCode === 'finished' || statusText === '已结束') {
            // 已结束的比赛不显示观看按钮
            processedMatch.watchInfo = null
            processedMatch.canWatch = false
          } else {
            // 默认情况：如果状态不明确，显示预约按钮
            processedMatch.watchInfo = {
              type: 'reserve',
              text: '预约',
              needReservation: true,
              price: 0,
              watchBtnClass: 'btn-reserve'
            }
            processedMatch.canWatch = true
          }
        }
        
        // 确保canWatch属性存在且为true
        if (processedMatch.canWatch === undefined || processedMatch.canWatch === null) {
          processedMatch.canWatch = true
        }
        
        return processedMatch
      })
    },
    
    // 加载日历数据
    async loadCalendarData(params = {}) {
      try {
        this.loading = true
        
        // 添加城市参数
        const requestParams = {
          ...params,
          page: params.page || 1,
          limit: params.limit || 20
        }
        
        // 从store获取城市信息
        const savedLocation = this.$store.state.location || this.$store.getters.getLocation
        if (savedLocation && (savedLocation.city || savedLocation.province)) {
          const cityName = savedLocation.city || savedLocation.province
          if (cityName && cityName !== '当前位置') {
            requestParams.city = cityName
          }
        }
        
        console.log('发送请求参数:', requestParams)
        const response = await getCalendarData(requestParams)
        
        if (response.code === 0 && response.data) {
          const { dates, matchTypes, matches, pagination } = response.data
          
          // 更新日期数据
          this.weekDates = dates || []
          
          // 更新比赛类型
          this.matchTypes = matchTypes || []
          
          // 处理比赛数据，确保状态正确
          this.matches = (matches || []).map(match => {
            // 确保每个比赛都有正确的状态信息
            if (!match.status) {
              // 根据时间判断状态
              const matchTime = new Date(match.time || match.match_time)
              const now = new Date()
              
              if (matchTime > now) {
                match.status = {
                  code: 'upcoming',
                  text: '未开始',
                  statusClass: 'status-upcoming'
                }
                // 只有未开始的比赛才能预约
                match.canWatch = true
              } else if (matchTime.toDateString() === now.toDateString()) {
                match.status = {
                  code: 'live',
                  text: '进行中',
                  statusClass: 'status-live'
                }
                // 进行中的比赛不显示按钮
                match.canWatch = false
                match.watchInfo = null
              } else {
                match.status = {
                  code: 'finished',
                  text: '已结束',
                  statusClass: 'status-finished'
                }
                // 已结束的比赛不显示按钮
                match.canWatch = false
                match.watchInfo = null
              }
            }
            return match
          })
          
          // 更新分页信息
          this.pagination = pagination || { total: 0, currentPage: 1, hasMore: false }
        } else if (response.code === 400) {
          // 处理"暂无比赛数据"的情况
          console.log('--- API返回暂无数据 ---')
          console.log('响应信息:', response.msg || '暂无比赛数据')
          
          // 清空比赛数据
          this.matches = []
          this.matchTypes = []
          this.pagination = { total: 0, currentPage: 1, hasMore: false }
          
          // 设置默认选中的日期
          const selectedDateItem = dates.find(date => date.isSelected)
          if (selectedDateItem) {
            this.selectedDate = selectedDateItem.date
          }
          
          // 设置今天的信息
          const todayItem = dates.find(date => date.isToday)
          if (todayItem) {
            this.todayInfo = {
              date: todayItem.date,
              text: `今天${todayItem.month}月${todayItem.day}日 ${todayItem.weekText}`
            }
          }
          
          // 设置默认选中的比赛类型
          const selectedMatchType = matchTypes.find(type => type.isSelected)
          if (selectedMatchType) {
            const index = matchTypes.findIndex(type => type.id === selectedMatchType.id)
            this.activeMatchType = index >= 0 ? index : 0
          }
          

        } else {
          console.error('API返回错误:', response.msg)
          uni.showToast({
            title: response.msg || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载日历数据失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 选择日期
    selectDate(date) {
      // 更新所有分组中的选中状态
      this.dateGroups = this.dateGroups.map(group => 
        group.map(item => ({
          ...item,
          isSelected: item.date === date
        }))
      )
      
      this.selectedDate = date
      
      // 重新加载该日期的比赛数据，包含城市参数
      this.loadCalendarData({ 
        date,
        page: 1,
        limit: 20
      })
    },
    
    // 切换比赛类型
    switchMatchType(index) {
      this.activeMatchType = index
      const selectedMatchType = this.matchTypes[index]
      
      // 可以选择重新加载数据或者仅在前端筛选
      // 这里我们选择前端筛选，如果需要重新请求API可以调用：
      // const matchTypeId = selectedMatchType && selectedMatchType.id
      // this.loadCalendarData({ 
      //   matchType: matchTypeId, 
      //   date: this.selectedDate,
      //   page: 1,
      //   limit: 20
      // })
    },
    

    
    // 观看比赛
    watchMatch(match) {      
      // 确保 watchInfo 存在
      if (!match.watchInfo) {
        match.watchInfo = {
          type: 'reserve',
          text: '预约'
        }
      }
      
      const watchType = match.watchInfo.type || 'reserve'
      const watchText = match.watchInfo.text || '预约'
      
      switch (watchType) {
        case 'free':
          // 直接进入观看页面
          uni.showToast({
            title: '正在进入直播间...',
            icon: 'loading'
          })
          break
          
        case 'reserve':
          // 跳转到预约页面
          if (match.id) {
            // 将比赛数据存储到全局状态，供预约页面使用
            const app = getApp()
            app.globalData = app.globalData || {}
            app.globalData.currentMatch = match
            
            console.log('跳转到预约页面，比赛数据:', match)
            uni.navigateTo({
              url: `/pages/cunba/book/index?matchId=${match.id}`
            })
          } else {
            uni.showToast({
              title: '比赛信息不完整',
              icon: 'none'
            })
          }
          break
          
        case 'paid':
          // 显示付费观看弹窗
          const price = match.watchInfo.price || 9.9
          uni.showModal({
            title: '付费观看',
            content: `观看 ${match.homeTeam.name} VS ${match.awayTeam.name} 需要支付 ¥${price}，是否继续？`,
            success: (res) => {
              if (res.confirm) {
                uni.showToast({
                  title: '正在跳转支付...',
                  icon: 'loading'
                })
              }
            }
          })
          break
          
        case 'replay':
          // 进入回放页面
          uni.showToast({
            title: '正在加载回放...',
            icon: 'loading'
          })
          break
          
        default:
          uni.showToast({
            title: '暂不支持此功能',
            icon: 'none'
          })
          break
      }
    },
    
    // 查看球队详情
    viewTeamDetail(team) {
      uni.navigateTo({
        url: `/pages/cunba/team_detail/index?teamId=${team.id || 1}&teamName=${encodeURIComponent(team.name)}`
      })
    },
    
    // 自定义导航栏切换事件
    onNavChange(navData) {
      // 导航栏切换处理
    },
    
    
    // 获取空状态文本
    getEmptyStateText() {
      const savedLocation = this.$store.state.location || this.$store.getters.getLocation
      const cityName = (savedLocation && savedLocation.address) || '当前位置'
      const currentMatchType = this.matchTypes[this.activeMatchType];
      if (currentMatchType) {
        return `${cityName}暂无${currentMatchType.name}比赛数据`;
      }
      return `${cityName}暂无比赛数据`;
    },
    
    // 获取空状态提示
    getEmptyStateTips() {
      const savedLocation = this.$store.state.location || this.$store.getters.getLocation
      const cityName = (savedLocation && savedLocation.address) || '当前位置'
      if (cityName === '当前位置') {
        return '请选择城市查看比赛数据';
      }
      return '请尝试选择其他城市或日期';
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}


/* 日期选择器 */
.date-selector {
  background: #ffffff;
  padding: 12px 8px;
  position: relative;
  margin-top: 80px;
  
  .date-swiper {
    height: 90px;
    width: 100%;
    
    .swiper-item {
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 4px;
    }
  }
  
  .date-week {
    display: flex;
    justify-content: space-around;
    height: 100%;
    align-items: center;
    width: 100%;
    
    .date-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 8px 2px;
      margin: 0 2px;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
      min-height: 70px;
      
      &.active {
        background: #4A90E2;
        
        .date-month,
        .date-day,
        .date-week-text {
          color: #fff;
        }
      }
      
      &.today {
        /* 移除红色边框 */
        /* border: 2px solid #FF6B35; */
        
        &:not(.active) {
          .date-day {
            color: #FF6B35;
            font-weight: bold;
          }
        }
      }
      
      .date-month {
        font-size: 11px;
        color: #666;
        margin-bottom: 1px;
        line-height: 1.2;
      }
      
      .date-day {
        font-size: 20px;
        font-weight: bold;
        color: #333;
        margin: 2px 0;
        line-height: 1;
      }
      
      .date-week-text {
        font-size: 11px;
        color: #666;
        margin-top: 1px;
        line-height: 1.2;
      }
    }
  }
  
  /* 滑动指示器 */
  .swiper-dots {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 8px;
    padding-bottom: 5px;
    
    .dot {
      width: 5px;
      height: 5px;
      border-radius: 50%;
      background: #ddd;
      margin: 0 2px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.active {
        background: #4A90E2;
        transform: scale(1.3);
      }
    }
  }
}

/* 赛事类型提示 */
.match-type-header {
  background: #fff;
  padding: 12px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  
  .current-date {
    font-size: 14px;
    font-weight: bold;
    color: #333;
  }
  
  .match-type-hint {
    font-size: 12px;
    color: #FF6B35;
  }
}

/* 赛事类型切换标签 */
.match-type-tabs {
  background: #fff;
  padding: 0 15px 12px;
  
  .tab-container {
    display: flex;
    background: #f8f9fa;
    border-radius: 20px;
    padding: 3px;
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 8px 16px;
      border-radius: 18px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      .tab-text {
        font-size: 14px;
        color: #666;
        font-weight: 500;
      }
      
      &.active {
        background: #4A90E2;
        
        .tab-text {
          color: #fff;
          font-weight: bold;
        }
      }
    }
  }
}

/* 比赛列表 */
.match-list {
  padding: 0 15px;
  
  .loading-container,
  .empty-container {
    background: #fff;
    border-radius: 12px;
    padding: 40px 15px;
    margin-bottom: 15px;
    text-align: center;
    
    .loading-text,
    .empty-text {
      font-size: 14px;
      color: #999;
      margin-bottom: 8px;
    }
    
    .empty-tips {
      font-size: 12px;
      color: #ccc;
    }
    
    .loading-text {
      color: #4A90E2;
      margin-bottom: 0;
    }
  }
  
}

/* 页面容器样式 */
.page-with-cunba-nav {
  padding-bottom: calc(80px + env(safe-area-inset-bottom));
  /* 日期选择器已经设置了margin-top，这里不需要重复设置padding-top */
}

/* 禁用页面过渡动画 */
// #ifdef H5
.uni-page {
  transition: none !important;
  animation: none !important;
}
// #endif
</style>
